﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using static Infra_common.Aes.AesModel;

namespace Infra_common.Aes
{
    public class Aes
    {
        public Aes(string appid, string Secret)
        {
            IV = appid;
            Key = Secret;
        }

        //获取配置文件的appid
        private string IV;
        //获取配置文件的密钥
        private string Key;
        //解密代码，将code转化为token的文本
        public string Decrypt(string encryptStr)
        {
            try
            {
                byte[] bKey = Encoding.UTF8.GetBytes(Key);
                byte[] bIV = Encoding.UTF8.GetBytes(IV);
                byte[] byteArray = strToToHexByte(encryptStr);
                Rijndael aes = Rijndael.Create();
                aes.Key = bKey;
                aes.IV = bIV;
                aes.Mode = CipherMode.CBC;
                aes.Padding = PaddingMode.None;
                aes.KeySize = bIV.Length == 16 ? 128 : 256;//16字符长度appID应用采用AES-128-CBC对称加密算法；原32字符长度appID应用依旧采用AES-256-CBC对称加密算法。
                aes.BlockSize = bIV.Length == 16 ? 128 : 256;
                var decrypt = "";
                using (MemoryStream mStream = new MemoryStream())
                {
                    using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateDecryptor(bKey, bIV), CryptoStreamMode.Write))
                    {
                        cStream.Write(byteArray, 0, byteArray.Length);
                        cStream.FlushFinalBlock();
                        decrypt = Encoding.UTF8.GetString(mStream.ToArray());
                    }
                }
                aes.Clear();
                return decrypt;
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        private byte[] strToToHexByte(string hexString)
        {
            try
            {
                hexString = hexString.Replace(" ", "");
                if ((hexString.Length % 2) != 0)
                    hexString += " ";
                byte[] returnBytes = new byte[hexString.Length / 2];
                for (int i = 0; i < returnBytes.Length; i++)
                    returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
                return returnBytes;
            }
            catch (Exception e)
            {
                throw e;
            }


        }
        //被外界调用的方法，传入code返回aesmodel对象
        public aesmodel GetToken(string code)
        {
            //AesModel obj = null;
            try
            {
                string AesModelObj = Decrypt(code);
                //aesmodel obj = JsonConvert.DeserializeObject<AesModel.aesmodel>(AesModelObj);
                //Encoding encoding = Encoding.UTF8;

                //因为有两种json返回值，所以先转成jobject
                JObject jobject = JObject.Parse(AesModelObj);
                if (jobject["visit_oauth"].ToString() == "False"|| jobject["visit_oauth"].ToString() == "false")
                {
                    //未授权传一个空的
                    return new aesmodel();
                }
                else
                {
                    return JsonConvert.DeserializeObject<aesmodel>(AesModelObj);
                }
                
            }
            catch (Exception e)
            {

                throw e;
                
            }

        }
    }
}
